/*
	TUIO Java backend - part of the reacTIVision project
	http://www.iua.upf.es/mtg/reacTable

	Copyright (c) 2005 Martin Kaltenbrunner <mkalten@iua.upf.es>

	Permission is hereby granted, free of charge, to any person obtaining
	a copy of this software and associated documentation files
	(the "Software"), to deal in the Software without restriction,
	including without limitation the rights to use, copy, modify, merge,
	publish, distribute, sublicense, and/or sell copies of the Software,
	and to permit persons to whom the Software is furnished to do so,
	subject to the following conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	Any person wishing to distribute modifications to the Software is
	requested to send the modifications to the original developer so that
	they can be incorporated into the canonical version.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
	IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
	ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
	CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
	WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import java.util.*;

public class TuioCocoaBind implements TuioListener 
{
   private TuioClient moTuioClient;
   private boolean mbDebug;

	private Hashtable objectList;	
	private Hashtable cursorList;	
   
   public TuioCocoaBind(){}
   
   // called from Cocoa 
   // 
   public void initialize( int piPort, boolean pbDebug ) throws Exception
   {
 		try
      {
         mbDebug = pbDebug;
         
         if( mbDebug )
            System.out.println( "Java Tuio init begins" );
         
         if( piPort < 1 || piPort > 65536 )
            throw new Exception( "port out of range (1-65536)" );
            
         objectList = new Hashtable();	
         cursorList = new Hashtable();	
         
         // The TuioClient was made static so it's reused for other 
         // instantiations of the Tuio patch (saves resources).
         // Because of this we only need to keep one object and cursor 
         // list and need only one listener
         //
         
         moTuioClient = new TuioClient( piPort ); 
         moTuioClient.addTuioListener( this );
         moTuioClient.connect();
            
         if( mbDebug )
            System.out.println( "Java Tuio started. Port: " + piPort );
        
         // }
        // else
        //{
         //   if( mbDebug )
        //       System.out.println( "Java Tuio already started. Port: " + piPort );
        // }
      }
      catch( Throwable e )
      {
         if( mbDebug )
            e.printStackTrace( System.out );
            
         throw new Exception( "Java Tuio init failed: " + e.getMessage() );
      }
   }
   
   public void addTuioObj(long s_id, int f_id) 
	{
		objectList.put(new Long(s_id),new TuioObject(s_id,f_id));
      if( mbDebug )
         System.out.println( "Java Tuio object added to list: " + s_id + ", fId: " + f_id );
	}

	public void updateTuioObj(long s_id, int f_id, float x, float y, float a, float X, float Y, float A, float m, float r) 
	{
		TuioObject tobj = (TuioObject)objectList.get(new Long(s_id));
		tobj.update(x,y,a,(float)Math.sqrt(X*X+Y*Y),A,m,r);
	}
	
	public void removeTuioObj(long s_id, int f_id) 
	{
		objectList.remove(new Long(s_id));
      
      if( mbDebug )
         System.out.println( "Java Tuio object removed from list: " + s_id + ", fId: " + f_id );
	}

	public void addTuioCur(long s_id) 
	{
		cursorList.put(new Long(s_id),new TuioObject(s_id,0));
		
		//if (!cursorList.containsKey(new Long(s_id))) 
		//{
		//	cursorList.put(new Long(s_id), new Vector());
		//}
	}

	public void updateTuioCur(long s_id, float x, float y, float X, float Y, float m) 
	{
		TuioObject tobj = (TuioObject)cursorList.get(new Long(s_id));
		tobj.update(x,y,0,0,0,0,0);
		//Vector pointList = (Vector)cursorList.get(new Long(s_id));
		//pointList.addElement(new Poinx,y);
	}
	
	public void removeTuioCur(long s_id) 
	{
		cursorList.remove(new Long(s_id));	
	}

	public void refresh() 
	{
	   // not needed
	}
   
   // called from Cocoa 
   // 
   public boolean getObjectInfo( TuioCocoaFiducialData pcoResultData, int piPort, int piFiducialId ) throws Exception
   {
      try
      {
         if( pcoResultData == null )
            throw new Exception( "pcoResultData is null" );
            
         if( piFiducialId < 0 )
            throw new Exception( "fiducial id out of range" );
            
         if( piPort != moTuioClient.port )
         {
            if( mbDebug )
               System.out.println( "Java Tuio port change unsupported. (fId: " + piFiducialId + ", port: " + piPort + ")" );
         }
                              
         for( Enumeration e = cursorList.keys(); e.hasMoreElements() ; ) 
         {
            TuioObject tobj = (TuioObject)cursorList.get( (Long)e.nextElement() );
            //TuioObject tobj = (TuioObject)cursorList[0];
			//if( tobj.session_id == piFiducialId )
            //{
               //if( mbDebug )
                 // System.out.println( "Java Tuio returning data (fId: " + tobj.session_id + "): " + tobj.xpos + ", " + tobj.ypos + ", " + tobj.angle );

               pcoResultData.setData( tobj.xpos, tobj.ypos, tobj.angle );
               return true;
            //}
         }
      }
      catch( Throwable e )
      {
         if( mbDebug )
            e.printStackTrace( System.out );
         throw new Exception( e.getMessage() );
      }
      return false;
   }
   
   // called from Cocoa 
   // 
   public void disconnect()
   {
      try
      {
         if( moTuioClient != null )
         {
            moTuioClient.disconnect();
         }
      }
      catch( Throwable e )
      {
        // if( mbDebug )
        //    e.printStackTrace( System.out );
      }
   }
}